package com.qianchang.microfinance.view.mine.loan;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.utils.ViewUtils;
import com.dm.library.widgets.OneLineLinearLayout;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.CashLoanDetailBean;
import com.qianchang.microfinance.bean.ProjectStatus;
import com.qianchang.microfinance.bean.RepayPlanAfterParams;
import com.qianchang.microfinance.bean.SubmitLoanBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.hsrecharge.HSReChargeActivity;
import com.qianchang.microfinance.view.mine.bill.PayBackActivity;
import com.qianchang.microfinance.view.mine.bill.PrePayBackActivity;
import com.qianchang.microfinance.view.mine.bill.RenewloanActivity;
import com.qianchang.microfinance.view.mine.bill.SettlementActivity;
import com.qianchang.microfinance.view.mine.renewal.RenewalApplyActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 借款详情
 * 所有类型的借款详情都在一起  initType()中判断区分
 * jinbailiang
 */
public class MyLoanDetailActivity extends BaseActivity {


    @BindView(R.id.tv_apply_amount)
    DTextView tvApplyAmount;
    @BindView(R.id.tv_deadline)
    DTextView tvDeadline;
    @BindView(R.id.tv_title_serviceFeeRate)
    DTextView tvTitleServiceFeeRate;
    @BindView(R.id.tv_serviceFeeRate)
    DTextView tvServiceFeeRate;
    @BindView(R.id.tv_repaymentType)
    DTextView tvRepaymentType;
    @BindView(R.id.tv_apply_date)
    DTextView tvApplyDate;
    @BindView(R.id.tv_bankCardInfo)
    DTextView tvBankCardInfo;
    @BindView(R.id.oll_mortgage_goods_info)
    OneLineLinearLayout ollMortgageGoodsInfo;
    @BindView(R.id.oll_reply_plan)
    OneLineLinearLayout ollReplyPlan;
    @BindView(R.id.oll_reply_record)
    OneLineLinearLayout ollReplyRecord;
    @BindView(R.id.oll_loan_advancerepayment)
    OneLineLinearLayout ollReplyAdvance;
    @BindView(R.id.oll_loan_agreement)
    OneLineLinearLayout ollLoanAgreement;
    @BindView(R.id.settlement_borrowing)
    OneLineLinearLayout settlement_borrowing;
    @BindView(R.id.oll_renewal_id)
    OneLineLinearLayout oll_renewal_id;
    @BindView(R.id.ll_click_layout)
    LinearLayout llClickLayout;
    @BindView(R.id.tv_msg)
    DTextView tvMsg;
    @BindView(R.id.rl_msg_btn_layout)
    LinearLayout rlMsg;
    @BindView(R.id.btn_sure_agreement)
    DButton btnSureAgreement;
    @BindView(R.id.ll_mortgage_type)
    LinearLayout llMortgageType;
    @BindView(R.id.tv_loan_usage)
    DTextView tvLoanUsage;


    private String projectId;
    private int projectType;
    private String urlType;
    private String url;
    private String monthInterestRate;

    private static final String TAG = "MyLoanDetailActivity";
    private String repaymentType;
    private String unit;
    private String status;
    private String applyAmount;
    private String statusDes;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_loan_detail);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleName(getString(R.string.title_loan_detail));
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (null != bundle) {
            projectId = bundle.getString(ConstantAppInfo.PROJECT_ID);
            projectType = bundle.getInt(ConstantAppInfo.PROJECT_TYPE);
            unit = bundle.getString(ConstantAppInfo.PROJECT_UNIT);
            status = bundle.getString(ConstantAppInfo.PROJECT_STATUS);
            statusDes = bundle.getString(ConstantAppInfo.PROJECT_STATUS_DES);
        }
        initType();
        getProjectDetail();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getProjectDetail();
    }

    private void getProjectDetail() {
        HttpParams params = new HttpParams();
        show();
        params.put("projectId", projectId);
        params.put("userType", "");
        params.put("projectType", projectType);
        DMOKHttpUtils.getInstance().post(this, url, params, new RequestCallBack<CashLoanDetailBean>() {
            @Override
            public void onSuccess(JsonResult<CashLoanDetailBean> response) {
                dismiss();
                if (response.isReqDataSuccess()) {
                    CashLoanDetailBean cashLoanDetailBean = response.getObject();
                    if (null != cashLoanDetailBean) {
                        refreshUi(cashLoanDetailBean);
                    }
                } else {
                    ToastUtil.getInstant().show(MyLoanDetailActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(MyLoanDetailActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void refreshUi(CashLoanDetailBean cashLoanDetailBean) {
        applyAmount = cashLoanDetailBean.getApplyAmount();
        tvApplyAmount.setTextContent(FormatUtil.numKbPointFormat(applyAmount));
        tvDeadline.setTextContent(cashLoanDetailBean.getDeadline());
        String serviceFeeRate = cashLoanDetailBean.getServiceFeeRate();
        tvServiceFeeRate.setTextContent(serviceFeeRate);
        if (null != serviceFeeRate && serviceFeeRate.contains("%")) {
            String[] split = serviceFeeRate.split("%");
            serviceFeeRate = split[0];
        }
        if ("0".equals(cashLoanDetailBean.getUnit())) {
            monthInterestRate = String.valueOf(StringUtils.toDouble(serviceFeeRate) * 30 / 100);
        } else {
            monthInterestRate = String.valueOf(StringUtils.toDouble(serviceFeeRate) / 100);
        }

        repaymentType = cashLoanDetailBean.getRepaymentType();
        tvRepaymentType.setTextContent(repaymentType);
        if ("0".equals(unit)) {
            repaymentType = "0";
        } else {
            repaymentType = "";
        }



        tvApplyDate.setTextContent(ViewUtils.formatDateToDay(cashLoanDetailBean.getApplyTime()));
        tvBankCardInfo.setTextContent(cashLoanDetailBean.getBankCardInfo());

        String purpose = cashLoanDetailBean.getPurpose();
        tvLoanUsage.setTextContent(switchPurs(purpose));
            if(!StringUtils.isEmpty(cashLoanDetailBean.getContinuedLoadStatus())){
                if(cashLoanDetailBean.getContinuedLoadStatus().equals("0")){
                    oll_renewal_id.setRightContent("不同意");
                    oll_renewal_id.setClickable(false);
                }
                if(cashLoanDetailBean.getContinuedLoadStatus().equals("1")){
                    oll_renewal_id.setRightContent("同意");
                    oll_renewal_id.setClickable(false);
                }
                if(cashLoanDetailBean.getContinuedLoadStatus().equals("2")){
                    oll_renewal_id.setRightContent("待审核");
                    oll_renewal_id.setClickable(false);
                }
            }else {
                oll_renewal_id.setRightContent("");
                oll_renewal_id.setClickable(true);
            }



        //isShowAdvanceSettle true 不显示  false不显示  lastPeriodIsOverdue true 显示 false
        if(cashLoanDetailBean.isLastPeriodIsOverdue()==true){
            settlement_borrowing.setVisibility(View.VISIBLE);
        }else {
            settlement_borrowing.setVisibility(View.GONE);
        }
        if(cashLoanDetailBean.isShowAdvanceSettle()==true){
            ollReplyAdvance.setVisibility(View.GONE);
            return;
        }
        //已结清
        if(cashLoanDetailBean.getStatus().equals("6") || cashLoanDetailBean.getStatus().equals("7")){
            ollReplyAdvance.setVisibility(View.VISIBLE);
        }else{
            ollReplyAdvance.setVisibility(View.GONE);
        }
    }

    private String switchPurs(String purpose){
        String type = "未知";
        if(purpose != null){
            switch (purpose){
                case "0":
                    type = "旅游";
                    break;
                case "1":
                    type = "教育";
                    break;
                case "2":
                    type = "电器";
                    break;
                case "3":
                    type = "装修";
                    break;
                default:
                    break;
            }
        }
        return type;
    }


    /**
     * 区分详情类型
     */
    private void initType() {
        //    CASH("0", "现金贷"),COST("1", "消费贷"),DIYA("2", "抵押贷"),HOUSE_RENT("3", "租房分期"),CAMPUS("4", "学生贷"),OWNER("5", "业主贷");
        switch (projectType) {
            case 0://现金贷
                llMortgageType.setVisibility(View.GONE);
                ollMortgageGoodsInfo.setVisibility(View.GONE);
                urlType = "cash";
                break;
            case 5://业主贷
                llMortgageType.setVisibility(View.GONE);
                ollMortgageGoodsInfo.setVisibility(View.GONE);
                urlType = "owner";
                break;
            case 4://学生贷
                llMortgageType.setVisibility(View.GONE);
                ollMortgageGoodsInfo.setVisibility(View.GONE);
                urlType = "campus";
                break;
            case 2://抵押贷
                urlType = "diya";
                llMortgageType.setVisibility(View.VISIBLE);
                ollMortgageGoodsInfo.setVisibility(View.VISIBLE);
                break;
            default:
                llMortgageType.setVisibility(View.GONE);
                ollMortgageGoodsInfo.setVisibility(View.GONE);
                break;
        }

        tvTitleServiceFeeRate.setText(getString(R.string.label_interest_rate));
//        switch (unit) {
//            case "0":
//
//                break;
//            case "1":
//                tvTitleServiceFeeRate.setText(getString(R.string.Label_monthly_interest_rate));
//                break;
//        }

        llClickLayout.setVisibility(View.GONE);
        rlMsg.setVisibility(View.VISIBLE);
        btnSureAgreement.setVisibility(View.GONE);
        switch (status) {
            case ProjectStatus.SHZ:
                tvMsg.setTextContent("借款进度当前为审核中，请耐心等待");
                break;
            case ProjectStatus.DQR:
                tvMsg.setTextContent("您提交的借款已审核通过，请确认合同");
                btnSureAgreement.setVisibility(View.VISIBLE);
                break;
            case ProjectStatus.DFK:
                tvMsg.setTextContent("放款结果将会以短信告知，请耐心等待");
                break;
            case ProjectStatus.DFP:
                tvMsg.setTextContent("借款进度当前为待分配，请耐心等待");
                break;
            case ProjectStatus.JJFK:
            case ProjectStatus.BTG:
            case ProjectStatus.JJQY:
                tvMsg.setTextContent("借款申请审核不通过，如需借款请重新提交申请，并保证填写申请信息真实");
                break;
            case ProjectStatus.HKZ:
            case ProjectStatus.YQ:
            case ProjectStatus.YJQ:
            case ProjectStatus.HZ:
                rlMsg.setVisibility(View.GONE);
                llClickLayout.setVisibility(View.VISIBLE);
                break;
        }

        url = DMConstant.Config.BASE_USER + "/loan/" + urlType + DMConstant.Config.V + "/detail.do";
    }


    @OnClick({R.id.oll_mortgage_goods_info, R.id.oll_reply_plan, R.id.oll_reply_record, R.id.oll_loan_agreement,
            R.id.ll_click_layout, R.id.btn_sure_agreement, R.id.rl_msg_btn_layout, R.id.oll_loan_advancerepayment,R.id.oll_renewal_id,R.id.settlement_borrowing})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        bundle.putString(ConstantAppInfo.PROJECT_ID, projectId);
        bundle.putString(ConstantAppInfo.PROJECT_TYPE, projectType + "");
        switch (view.getId()) {
//            case R.id.oll_mortgage_goods_info: //押品信息
//                startActivity(MortgageGoodsInfoActivity.class, bundle);
//                break;
            case R.id.oll_reply_plan:    //还款计划
                RepayPlanAfterParams params = new RepayPlanAfterParams(projectId, monthInterestRate, repaymentType);
                bundle.putSerializable(RepayPlanAfterParams.class.getName(), params);
                bundle.putDouble("applyAmount", Double.parseDouble(applyAmount)); //借款金额
                startActivity(RepayPlanActivity.class, bundle);
                break;
            case R.id.oll_reply_record:   //还款记录
                startActivity(RepaymentRecordActivity.class, bundle);
                break;
            case R.id.oll_loan_agreement: //借款合同
                startActivity(LoanAgreementActivity.class, bundle);
                break;
            case R.id.btn_sure_agreement:   //确认合同
                bundle.putString(ConstantAppInfo.PROJECT_ID, projectId);
                bundle.putInt(ConstantAppInfo.PROJECT_TYPE, projectType);
                bundle.putString(ConstantAppInfo.PROJECT_STATUS_DES, statusDes);
                bundle.putString(SubmitLoanBean.LOAN_AMOUNT, applyAmount);
                bundle.putInt(ConstantAppInfo.FROM, 1);
                startActivity(ConfirmAgreementActivity.class, bundle, true);
                break;
            case R.id.oll_loan_advancerepayment: //提前还款
                startActivity(PrePayBackActivity.class, bundle);
                break;
            case R.id.oll_renewal_id:           //续贷申请

          //    startActivity(RenewalApplyActivity.class);
               startActivity(RenewloanActivity.class,bundle);

//                final AlertDialog alertDialog = new AlertDialog.Builder(MyLoanDetailActivity.this)
//                        .setTitle("续贷")
//                        .setMessage("是否执行一键续贷？")
//                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        })
//                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                //执行提前还款
//                                dialog.dismiss();
//
//                            }
//                        }).setCancelable(false).create();
//                alertDialog.show();



                break;
            case R.id.settlement_borrowing://结清借款
                bundle.putString(ConstantAppInfo.PROJECT_ID, projectId);
                startActivity(SettlementActivity.class,bundle,true);

                break;
        }
    }

}
